package com.gxc.datacore.metadata.util;

import com.gxc.datacore.db.cache.DbPool;
import com.gxc.datacore.metadata.domain.Database;
import com.gxc.datacore.metadata.domain.Table;
import com.gxc.datacore.metadata.service.DatabaseService;
import com.gxc.datacore.metadata.service.TableService;
import com.gxc.dbcore.dao.SqlDao;
import com.gxc.webcore.util.ContextUtil;

public class SqlDaoUtil {

	/**
	 * 获取table对应的sqlDao
	 * 
	 * @param table_id
	 * @return
	 */
	public static SqlDao getSqlDaoByTable(String table_id) {
		TableService tableService = (TableService) ContextUtil
				.getBean(TableService.class);
		Table table = tableService.retrieve(table_id);
		if (table != null) {
			return SqlDaoUtil.getSqlDaoByDatabase(table.getDatabase_id());
		}
		return null;
	}

	/**
	 * 获取table对应的SqlDao
	 * 
	 * @param table
	 * @return
	 */
	public static SqlDao getSqlDaoByTable(Table table) {
		if (table != null) {
			return SqlDaoUtil.getSqlDaoByDatabase(table.getDatabase_id());
		}
		return null;
	}

	/**
	 * 获取database对应的sqlDao
	 * 
	 * @param database_id
	 * @return
	 */
	public static SqlDao getSqlDaoByDatabase(String database_id) {
		SqlDao sqlDao = DbPool.getSqlDao(database_id);
		if (sqlDao == null) {
			DatabaseService databaseService = (DatabaseService) ContextUtil
					.getBean(DatabaseService.class);
			Database database = databaseService.retrieve(database_id);
			if (database != null) {
				DbPool.create(database_id,
						DataSourceUtil.parseToDataSource(database));
				sqlDao = DbPool.getSqlDao(database_id);
			}
		}
		return sqlDao;
	}

	/**
	 * 获取database对应的sqlDao
	 * 
	 * @param database_id
	 * @return
	 */
	public static SqlDao getSqlDaoByDatabase(Database database) {
		if (database != null) {
			SqlDao sqlDao = DbPool.getSqlDao(database.getId());
			if (sqlDao == null) {
				DbPool.create(database.getId(),
						DataSourceUtil.parseToDataSource(database));
				sqlDao = DbPool.getSqlDao(database.getId());
			}
			return sqlDao;
		}
		return null;
	}

}
